<?php

namespace App\Http\Controllers\Admin;

use App\Goods;
use App\Http\Response;
use App\Spec;
use App\SpecItem;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class SpecController extends Controller
{
    use Response;

    public function index(Request $request)
    {
        $is_page = $request->get('is_page');
        if ($is_page) {
            $data = Spec::with(['goods_type'])->where('goods_type_id', $request->get('goods_type_id'))->orderBy('sort', 'desc')->paginate($request->get('pageSize'), '*', 'pageNo');
        } else {
            $data = Spec::with(['goods_type', 'spec_items'])->where('goods_type_id', $request->get('goods_type_id'))->orderBy('sort', 'desc')->get();
        }
        return $this->success(200, $data);
    }

    public function store(Request $request)
    {
        DB::beginTransaction();
        try {
            $created = Spec::create($request->all());
            if ($created) {
                $item = explode(PHP_EOL, $request->get('input_list'));
                if ($item){
                    foreach ($item as $key => $value) {
                        $data = [
                            'spec_id' => $created->id,
                            'item' => $value
                        ];
                        SpecItem::create($data);
                    }
                }

            }
            DB::commit();
            return $this->message(200, '添加成功');
        } catch (\Exception $exception) {
            Log::error("添加spec",[$exception->getMessage()]);
            DB::rollBack();
            return $this->message(505,'添加失败');
        }

    }

    public function show($id)
    {
        $data = Spec::find($id);
        return $this->success(200, $data);
    }

    public function update($id, Request $request)
    {
        DB::beginTransaction();
        try {
            Spec::where('id', $id)->update($request->all());
            SpecItem::where('spec_id', $id)->delete();
            $item = explode(PHP_EOL, $request->get('input_list'));
            foreach ($item as $key => $value) {
                $data = [
                    'spec_id' => $id,
                    'item' => $value
                ];
                SpecItem::create($data);
            }
            DB::commit();
            return $this->message(200, '修改成功');
        } catch (\Exception $exception) {
            DB::rollBack();
            return $this->message(505, '修改失败');

        }
    }

    public function destroy($id,Request $request)
    {
        DB::beginTransaction();
        try {
            Spec::destroy($id);
            SpecItem::where('spec_id', $id)->delete();
            DB::commit();
            return $this->message(200, '删除成功');
        } catch (\Exception $exception) {
            DB::rollBack();
            return $this->message(505, '删除失败');
        }
    }
}
